package com.dongdong.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.dongdong.constant.Constant;
import com.dongdong.constant.RedisUtil;
import com.dongdong.result.Result;
import com.dongdong.result.ResultEnums;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/send")
public class SendMessageController {

    @Value("${ali.accessKeyId}")
    private String accessKeyId;

    @Value("${ali.accessKeySecret}")
    private String accessKeySecret;

    @Value("${ali.region}")
    private String region;

    @Value("${ali.setEndpointOverride}")
    private String setEndpointOverride;

    @Value("${ali.signName}")
    private String signName;

    @Value("${ali.templateCode}")
    private String templateCode;


    @Autowired
    private StringRedisTemplate redisTemplate; //缓存


    @GetMapping("/message")
    public Result message(String phone){
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(region) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride(setEndpointOverride)
                )
                .build();
        //生成随机验证码
        String code=RandomUtil.randomNumbers( 6);
        JSONObject jsonObject = new JSONObject();//{code:666}
        jsonObject.put("code", code);
        String codeStr = JSONObject.toJSONString(jsonObject);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phone)
                .templateParam(codeStr)
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String json = new Gson().toJson(resp);
        System.out.println(new Gson().toJson(resp));

        client.close();

//        redisTemplate.boundHashOps(RedisUtil.YANZHENGMA).put(phone, code);
//        redisTemplate.expire(phone,50, TimeUnit.SECONDS); //1分钟过期
//        redisTemplate.boundValueOps(RedisUtil.YANZHENGMA+phone).set(code); //不过期
//        redisTemplate.boundValueOps(RedisUtil.YANZHENGMA+phone).set(code,60, TimeUnit.SECONDS); //存值 60秒
//            String value = redisTemplate.boundValueOps(RedisUtil.YANZHENGMA+phone).get();  //取值
//            System.out.println(value);

        redisTemplate.opsForValue().set(phone,code);//60分钟




        return Result.RESPONSE(ResultEnums.SENDMESSAGE_SUCCESS).setData(code);
    }

    public static void main(String[] args) {
        String s = RandomUtil.randomNumbers(  6);
        System.out.println(s);
    }

}
